<?php
/**
 * CreateTime: 2023/7/24 10:24
 */

namespace App\Http\Controllers\Login;

use App\Func\EncryptionFunc;
use App\Func\RequestFunc;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Http\Controllers\Controller;
use App\Http\pkConfig\login\PkLoginConfigGet;
use App\Http\Requests\Login\LoginV2Request;
use App\Http\Requests\Login\SwitchDepartmentRequest;
use App\Models\Staff\StaffDepartmentModel;
use App\Models\Staff\StaffModel;
use App\Scopes\MediationStaffScope;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;

class LoginV2Controller extends Controller
{
    public function getLoginPuKey()
    {
        $data = request()->all();
        if(!isset($data['login_token'])){
            return ResponseFunc::returnJson(
                'error',
                null,
                "当前用户不存在",
                200
            );
        }
        $staffModel = new StaffModel();
        // 查询用户公钥
        $staffInfo = $staffModel->select([
            'pu_key',
            'staff_id',
        ])->withoutGlobalScopes()
        ->where('staff_login_account',$data['login_token'])->first();
        if(!isset($staffInfo['pu_key'])){
            return ResponseFunc::returnJson(
                'error',
                null,
                "当前用户不存在",
                200
            );
        }

    return ResponseFunc::returnJson(
            'ok',
            [
                'pu_key' => $staffInfo['pu_key']
            ],
            "获取用户公钥成功",
            200
        );

    }

    public function switchStaffLogin(SwitchDepartmentRequest $request){
        $departmentId = $request->all()['department_id'];
        $requestId = RequestFunc::getHeaderParams("U-TK");
        // 解密token
        // 通过Rsa解密获取redis中正确的key
        $encryptionFunc = new EncryptionFunc();
        $adminLoginPkConfig = new PkLoginConfigGet();
        $redisKey = $encryptionFunc->rsaToBase64Decode($adminLoginPkConfig->getPrKey(),$requestId);
        $isExist = Redis::exists($redisKey);
        if($isExist){
            $staffInfo = TokenFuc::getCurrentStaffInfo();
//            if($staffInfo['department_id'] == $departmentId){
//                return ResponseFunc::returnJson(
//                    'error',
//                    null,
//                    "不能切换至当前部门",
//                    200
//                );
//            }
            // 校验这个用户是否属于当前部门
            $staffDeptModel = new StaffDepartmentModel();
            $checkDept = $staffDeptModel->isExistByCondition(
                [
                    'staff_id' => $staffInfo['staff_id'],
                    'department_id' => $departmentId
                ]
            );
            if(!$checkDept){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    "当前用户不属于该部门",
                    200
                );
            }
            $staffInfo['department_id'] = $departmentId;
            // 用系统通用的公钥加密
            // 根据IP_时间_用户名生成token
            $ip = RequestFunc::getIP();
            $staffInfo['ip'] = $ip;
            $tokenEncryptionStr = $encryptionFunc->rsaToBase64Encode($adminLoginPkConfig->getPuKey(),$redisKey);
            $code = Redis::setex($redisKey,3600,serialize($staffInfo));
            return ResponseFunc::returnJson(
                'ok',
                [
                    'token' => $tokenEncryptionStr
                ],
                "登录成功",
                200
            );
        }else{
            return ResponseFunc::returnJson(
                'error',
                null,
                "切换部门失败",
                200
            );
        }
    }

    public function login(LoginV2Request $request){
            $adminLoginPkConfig = new PkLoginConfigGet();
            $encryptionFunc = new EncryptionFunc();
            $data = $request->all();
            // 获取用户私钥
            $staffModel = new StaffModel();
            $staffInfo = $staffModel->select([
                'pv_key',
                'staff_id',
                'staff_login_account',
                'company_id',
                'staff_login_password',
                'staff_type',
            ])->withoutGlobalScopes()
            ->where('staff_login_account',$data['login_token'])
            ->where('staff_status',1)
            ->where('status',1)
            ->first();


            if(!$staffInfo){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    "当前用户不存在",
                    200
                );
            }

            $aseKey = $encryptionFunc->rsaToBase64Decode($staffInfo['pv_key'],$data['sign']);
            if(!$aseKey){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    "签名验证失败",
                    200
                );
            }

            // 解析账号密码
            $account = $encryptionFunc->Aes256cbcPkcs7ToBase64Decode($aseKey,$data['staff_login_account']);
            $root_password = $encryptionFunc->Aes256cbcPkcs7ToBase64Decode($aseKey,$data['staff_login_password']);

            // 校验两个密码加密后是否一致
            if (!(Hash::check($root_password, $staffInfo['staff_login_password']))) {
                // 密码验证失败
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    "账号或密码不匹配",
                    200
                );
            }
            // 刷新最后登录日期
            $staffModel
                ->withoutGlobalScopes()
                ->where('staff_id',$staffInfo['staff_id'])->update([
                'staff_last_login_time' => date("Y-m-d h:i:s",time())
            ]);

            // 根据IP_时间_用户名生成token
            $ip = RequestFunc::getIP();
            // 调解中心登录
            $tokenStr = "api_login_mediation_staff_v2_".$staffInfo['staff_id'];
            // 用系统通用的公钥加密
            $tokenEncryptionStr = $encryptionFunc->rsaToBase64Encode($adminLoginPkConfig->getPuKey(),$tokenStr);
            $tokenValue = [
                'ip' => $ip,
            ];
            // 查询当前用户登录默认登录部门
            $departStaffModel = new StaffDepartmentModel();
            $departId = $departStaffModel
                ->select(['department_id'])
                ->where('staff_id',$staffInfo['staff_id'])
                ->first();
            $tokenValue['department_id'] = $departId['department_id'];

            $tokenValue = array_merge($staffInfo->toArray(),$tokenValue);
            // 过期时间设置的一个小时
            $code = Redis::setex($tokenStr,3600,serialize($tokenValue));
            return ResponseFunc::returnJson(
                'ok',
                [
                    'token' => $tokenEncryptionStr
                ],
                "登录成功",
                200
            );
    }
}